﻿using System.Threading;
using Iorz.DomainSearch.Utils.Tools;

namespace Iorz.DomainSearch.Utils.Provider
{
    public class XinnetProvider : IProvider
    {
        private int mTryCount = 1;

        private string mLog = "Error_Xinnet.log";

        public string GetName()
        {
            return "新网";
        }

        public bool Search(string domain, out bool isAvail)
        {
            return CheckDomainAvail(domain, out isAvail);
        }

        private bool CheckDomainAvail(string domain, out bool isAvail)
        {
            isAvail = false;

            var response = HttpHelper.GetHtml(new HttpHelper.HttpRequest()
            {
                Method = HttpHelper.HttpMethod.GET,
                UserAgent = "Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
                Url = GetUrl(domain)
            });

            if (response.Exception == null
                && !string.IsNullOrEmpty(response.Html))
            {
                var yes = response.Html.IndexOf("\"no\":[]") != -1;
                var no = response.Html.IndexOf("\"yes\":[]") != -1;

                if (yes || no)
                {
                    if (yes)
                    {
                        Tracker.Log("domain.log", domain);
                        isAvail = true;
                    }
                    else
                        return true;
                }
            }

            if (response.Exception == null)
                Tracker.Log(mLog, response.Html);
            else
                Tracker.Log(mLog, response.Exception.Message);

            if (mTryCount <= 3)
            {
                mTryCount++;
                Thread.Sleep(3000);
                return CheckDomainAvail(domain, out isAvail);
            }

            return false;
        }

        private string GetUrl(string domain)
        {
            var arr = domain.Split('.');
            return $"http://checkdomain.xinnet.com/domainCheck?callbackparam=jQuery17206919775903242649_{DateHelper.GetTimestamp4Millisecond()}&searchRandom=3&prefix={arr[0]}&suffix=.{arr[1]}&_={DateHelper.GetTimestamp4Millisecond()}";
        }
    }
}
